package wanba.wanbatv.com.wudao.sqlite;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 俞亚楠 on 2015/6/24.
 */
public class DBManager {
    private DBOpenHelper helper;
    private SQLiteDatabase db;

    public DBManager(Context context) {
        helper = new DBOpenHelper(context);
        // 因为getWritableDatabase内部调用了mContext.openOrCreateDatabase(mName, 0,
        // mFactory);
        // 所以要确保context已初始化,我们可以把实例化DBManager的步骤放在Activity的onCreate里
        db = helper.getWritableDatabase();
    }

    /**
     *
     * 添加一条记录
     *
     * @param person
     */
    public void add(Person person) {
        db.execSQL("insert into tbl_person values(null,?)", new Object[] { person.getName() });

    }

    /**
     * 添加多条记录
     *
     * @param persons
     */
    public void adds(List<Person> persons) {
        db.beginTransaction();
        try {
            for (Person p : persons) {
                db.execSQL("insert into tbl_person values(null,?)", new Object[] { p.getName()});
            }
            db.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            db.endTransaction();
        }
    }

    /**
     * 更新一条记录
     *
     * @param person
     */
    public void update(Person person) {
        db.execSQL("update tbl_person set name=?where _id=?", new Object[]{person.getName(), person.get_id()});
    }

    /**
     * 删除一条记录
     *
     * @param
     */
    public void delete(int id) {
        db.execSQL("delete from tbl_person where _id=?", new Object[] { id });
    }

    /**
     * 查询一条记录
     */
    public Person queryOne(int _id) {
        Person person = new Person();
        Cursor c = db.rawQuery("select * from tbl_person where _id=? order by _id asc", new String[] { _id + "" });
        while (c.moveToNext()) {
            person.set_id(c.getInt(c.getColumnIndex("_id")));
            person.setName(c.getString(c.getColumnIndex("name")));

        }
        c.close();
        return person;
    }


    /**
     * 查询多条记录
     *
     * @return List<Person>
     */
    public List<Person> queryMany() {
        ArrayList<Person> persons = new ArrayList<Person>();
        Cursor c = db.rawQuery("select * from tbl_person", null);
        while (c.moveToNext()) {
            Person person = new Person();
            person.set_id(c.getInt(c.getColumnIndex("_id")));
            person.setName(c.getString(c.getColumnIndex("name")));
            persons.add(person);
        }
        c.close();
        return persons;
    }

}
